﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using mshtml;
using System.Text.RegularExpressions;
using System.Data.SQLite;
using System.Data;

namespace nrtech.bot.compras.bll
{
    public static class startMonitor
    {
        static ArrayList listaSuspensoes;
        static ArrayList listaSuspensoesPregoes;
        static ArrayList listaAcompanhar;

        static ArrayList linhasTabelaSuspensoes;
        static ArrayList linhasTabelaMensagens;
        static String linhaTituloTabela; 
        static String linhaTituloMensagens;
        static String assuntoEmailMensagens;
        static ArrayList listaUsuarios;

        public static String monitorar(String tipoChamada /*M = Manual | A = Automática*/, String tags)
        {
            try
            {
                listaSuspensoes = new ArrayList();
                listaAcompanhar = new ArrayList();

                linhasTabelaSuspensoes = new ArrayList();
                linhasTabelaMensagens = new ArrayList();
                listaSuspensoesPregoes = new ArrayList();

                listaUsuarios = new ArrayList();
                DataSet dsUsers = Config.getUsers();
                foreach (DataRow row in dsUsers.Tables[0].Rows)
                    listaUsuarios.Add(row[0].ToString());

                bool enviarEmail = false;
                bool novasMensagens = false;

                foreach (String user in listaUsuarios)
                {
                    Config.lerConfig(user);

                    if (tipoChamada.Equals("M"))
                        Config.tags = tags;

                    Constants.defineNavegador(null);

                    Constants.wbNaveg.Navigate(Config.url + Constants.URL_LOGIN);
                    while (Constants.wbNaveg.ReadyState != WebBrowserReadyState.Complete)
                        Application.DoEvents();

                    HtmlElement campoUser = getElement("txtUserName");
                    HtmlElement campoPass = getElement("txtPassword");

                    if (campoUser == null || campoPass == null)
                        return @"Campos necessários para o LOGIN não foram encontrados na URL '" + Config.url + Constants.URL_LOGIN + "'.";

                    campoUser.SetAttribute("value", Config.userSite);
                    campoPass.SetAttribute("value", Config.passSite);

                    Constants.wbNaveg.Document.InvokeScript("frmLogin_submit");

                    while (!Constants.wbNaveg.Url.ToString().Equals(@"https://www.comprasnet.gov.br/"))
                        Application.DoEvents();

                    while (Constants.wbNaveg.ReadyState != WebBrowserReadyState.Complete)
                        Application.DoEvents();

                    Constants.wbNaveg.Navigate(@Config.url + Constants.URL_ACOMPANHAR);
                    while (Constants.wbNaveg.ReadyState != WebBrowserReadyState.Complete)
                        Application.DoEvents();

                    Constants.wbNaveg.Navigate(@Config.url + Constants.URL_ACOMPANHAR2);
                    while (Constants.wbNaveg.ReadyState != WebBrowserReadyState.Complete)
                        Application.DoEvents();

                    extrairLinksAcompanharSuspensao();
                    String conteudoEmail;

                    if (listaSuspensoes.Count > 0)
                    {
                        conteudoEmail = "<html><head></head><body>LISTA DE SUSPENSÕES ADMINISTRATIVAS (" + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") +
                            ")<br><br><table border=\"0\" cellspacing=\"1\" " +
                            "cellpadding=\"2\" class=\"tex3\" style=\"width: 100%; height: 172px\" width=\"100%\">" +
                            @linhaTituloTabela;

                        foreach (String linha in linhasTabelaSuspensoes)
                        {
                            conteudoEmail += Regex.Replace(linha, @"#", @Config.url + @Constants.URL_MOTIVO_SUSPENSAO +
                                listaSuspensoesPregoes[linhasTabelaSuspensoes.IndexOf(linha)]);
                            Application.DoEvents();
                        }

                        mailSender.sender(conteudoEmail + "</table></body></html>", "Suspensões");
                    }

                    foreach (String pregao in listaAcompanhar)
                    {
                        Constants.wbNaveg.Navigate(@Config.url + Constants.URL_MENSAGENS + pregao);
                        while (Constants.wbNaveg.ReadyState != WebBrowserReadyState.Complete)
                            Application.DoEvents();
                        extrairMensagens();


                        if (linhasTabelaMensagens.Count > 0)
                        {
                            conteudoEmail = "<html><head></head><body>" + linhaTituloMensagens +
                                "<br><br><table border=\"0\" cellspacing=\"1\" " +
                                "cellpadding=\"2\" class=\"tex3\" style=\"width: 100%; height: 172px\" width=\"100%\">";

                            foreach (String linha in linhasTabelaMensagens)
                            {
                                conteudoEmail += linha;
                            }

                            mailSender.sender(conteudoEmail + "</table></body></html>", "Mensagens Pregão " + assuntoEmailMensagens);
                        }

                        linhasTabelaMensagens.Clear();
                        Application.DoEvents();
                    }
                }
                Constants.wbNaveg.Navigate(@Config.url);
            }
            catch (Exception e)
            {
                return e.Message;
            }
            finally
            {
                Config.ultimoMonitor = DateTime.Now.ToString("HH:mm:ss");
                Config.ajustaHoraMonitor(DateTime.Now);
                Config.salvaProximoMonitor();
            }

            return null;
        }

        private static void extrairMensagens()
        {
            var tb = Constants.wbNaveg.Document.All[0];
            var top = Constants.wbNaveg.Document.All[0];

            foreach (HtmlElement elem in Constants.wbNaveg.Document.All)
            {
                if (elem.GetAttribute("className").Equals("td"))
                {
                    tb = elem;
                    break;
                }
            }

            foreach (HtmlElement elem in Constants.wbNaveg.Document.All)
            {
                if (elem.GetAttribute("className").Equals("tex3"))
                {
                    top = elem;
                    linhaTituloMensagens = @top.OuterHtml;
                    assuntoEmailMensagens = @top.Children[0].Children[0].Children[0].InnerText.Substring(top.Children[0].Children[0].Children[0].InnerText.Length - 6);
                    break;
                }
                Application.DoEvents();
            }

            Boolean inserirMsg = false;
            String[] tags = Config.tags.Split(',');
            foreach (HtmlElement tr in tb.Children[0].Children)
            {
                if (tags.Length == 0)
                    inserirMsg = true;
                else
                {
                    foreach (String tag in tags)
                    {
                        if (tr.Children[1].InnerText.Contains(tag))
                        {
                            inserirMsg = true;
                            break;
                        }
                    }
                }

                if (inserirMsg)
                {
                    if (!mensagemGravada(tr.Children[0].InnerText) || Config.reenvia)
                    {
                        linhasTabelaMensagens.Add(tr.OuterHtml);
                        
                        if (!mensagemGravada(tr.Children[0].InnerText))
                        gravaMensagens(tr.Children[0].InnerText);
                    }
                }

                Application.DoEvents();
            }
        }

        private static void extrairLinksAcompanharSuspensao()
        {
            var tb = Constants.wbNaveg.Document.All[0];
            foreach (HtmlElement elem in Constants.wbNaveg.Document.All)
            {
                if (elem.GetAttribute("className").Equals("tblPregao"))
                {
                    tb = elem;
                    break;
                }
                Application.DoEvents();
            }

            foreach (HtmlElement tr in tb.Children[0].Children)
            {
                //título da tabela
                if (tr.Children[0].InnerText.Equals("-"))
                {
                    linhaTituloTabela = tr.InnerHtml;
                    continue;
                }

                if (tr.Children[0].InnerText.Contains("Suspensão"))
                {
                    if (!mensagemGravada(tr.Children[0].InnerText + tr.Children[1].InnerText + tr.Children[2].InnerText) || Config.reenvia)
                    {
                        listaSuspensoes.Add("Suspensão Administrativa - " + tr.Children[1].InnerText + " - " +
                            tr.Children[2].InnerText + " - " + tr.Children[3].InnerText);
                        linhasTabelaSuspensoes.Add(tr.OuterHtml);
                        listaSuspensoesPregoes.Add(tr.Children[1].InnerHtml.Substring(24, 6));

                        if (!mensagemGravada(tr.Children[0].InnerText + tr.Children[1].InnerText + tr.Children[2].InnerText))
                        gravaMensagens(tr.Children[0].InnerText + tr.Children[1].InnerText + tr.Children[2].InnerText);
                    }

                } 
                else
                if (tr.Children[0].InnerText.Contains("Acompanhar"))
                {
                    listaAcompanhar.Add(tr.Children[1].InnerHtml.Substring(24,6));
                }

                Application.DoEvents();
            }
        }

        private static HtmlElement getElement(String name)
        {
            return Constants.wbNaveg.Document.GetElementById(name);
        }

        public static bool mensagemGravada(String id)
        {
            try
            {
                Constants.createConnection();
                SQLiteCommand comando = new SQLiteCommand(@"select _id from mensagens where identificacao = '" + id + "'", Constants.conn);
                SQLiteDataReader drMsg = comando.ExecuteReader();

                if (drMsg.HasRows)
                    return true;
            }
            catch (Exception e)
            {
                throw e;
            }
            return false;
        }
        
        public static void gravaMensagens(String id)
        {
            try
            {
                SQLiteTransaction trans;
                Constants.createConnection();
                SQLiteCommand comando = new SQLiteCommand(@"INSERT INTO mensagens (identificacao, dataEnvio) VALUES (@identificacao, @dataEnvio)");
                comando.Parameters.AddWithValue("@identificacao", id);
                comando.Parameters.AddWithValue("@dataEnvio", DateTime.Now);
                comando.Connection = Constants.conn;

                trans = Constants.conn.BeginTransaction();

                try
                {
                    comando.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    trans.Rollback();
                    throw e;
                }
                finally
                {
                    trans.Commit();
                    comando.Dispose();
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

    }
    
}
